/**    
 * @{#} RegisterActivity.java Create on 2014-5-26 下午9:51:05    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.adapter.BaseListAdapter;
import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.umeng.analytics.MobclickAgent;

public class MyXuanshangActivity extends BasicActivity implements
		OnRefreshListener<ListView> {

	PullToRefreshListView list_my_xuanshang;
	HashMap<String, Object> params = new HashMap<String, Object>();
	int start_qid;
	ArrayList<Object> array = new ArrayList<Object>();
	MyXuanshangAdapter adapter;
	private TextView text_empty;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_xuanshang);
		init();

		setNavTitle("我的悬赏");

		params.put(Constant.PARAM_API, "Question.GetList");
		params.put("pageSize", Constant.pageSize);
		params.put("Is_Cost", 1);
		try {
			params.put("uid", GlobalSettings.sUser.Uid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);

		list_my_xuanshang = (PullToRefreshListView) findViewById(R.id.list_my_xuanshang);

		list_my_xuanshang.setOnRefreshListener(this);

		list_my_xuanshang.setPullLoadEnabled(false);
		list_my_xuanshang.setPullRefreshEnabled(false);
		list_my_xuanshang.setScrollLoadEnabled(true);

		list_my_xuanshang.doPullRefreshing(true);

		list_my_xuanshang.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int arg2, long arg3) {
				JSONObject object = (JSONObject) view.getTag(R.id.tag_obj);
				Intent intent = new Intent(activity,
						QuestionDetailActivity.class);
				intent.putExtra(Constant.IDENTITY_KEY, object.toString());
				startActivity(intent);
			}
		});

		text_empty = (TextView) findViewById(R.id.text_empty);
		text_empty.setText("暂无悬赏问题");
	}

	public void loadData(boolean isShowDialog) {
		params.put("startQid", start_qid);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						list_my_xuanshang.onPullDownRefreshComplete();
						list_my_xuanshang.onPullUpRefreshComplete();
						list_my_xuanshang.setLastUpdateTime();
						if (!CommonUtility.isNull(o)) {
							try {
								JSONObject object = (JSONObject) o;
								if (CommonUtility.response200(object)) {
									object = object.getJSONObject("Res");

									JSONArray arr = (JSONArray) object
											.getJSONArray("Questions");
									if (arr.length() > 0) {
										CommonUtility.putAll(array, arr, true);
										if (CommonUtility.isNull(adapter)) {
											adapter = new MyXuanshangAdapter(
													activity, array);
											list_my_xuanshang
													.setAdapter(adapter);
										} else {
											adapter.notifyUpdate();
										}
										if (arr.length() < Constant.pageSize) {
											list_my_xuanshang
													.setHasMoreData(false);
										} else {
											list_my_xuanshang
													.setHasMoreData(true);
										}
									} else {
										if (array.size() > 0) {
											list_my_xuanshang
													.setHasMoreData(false);
										}
									}
									if (array.size() > 0) {
										start_qid = ((JSONObject) array
												.get(array.size() - 1))
												.getInt("Qid");
										text_empty.setVisibility(View.GONE);
									} else {
										text_empty.setVisibility(View.VISIBLE);
									}
								} else {
									CommonUtility.toast(activity,
											R.string.server_unavailable);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}), isShowDialog, params);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		start_qid = 0;
		array.clear();
		loadData(false);
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData(false);
	}

	public static class MyXuanshangAdapter extends BaseListAdapter {

		Activity activity;

		public MyXuanshangAdapter(Activity activity, ArrayList<Object> array) {
			super(activity, array);
			this.activity = activity;
		}

		class ViewHolder {
			TextView text_cost, text_create_cost_date, text_content,
					text_cancel_xuanshang, text_jiedan_time, text_doctor_name,
					text_jiedan_status;
			LinearLayout ll_detail;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup root) {
			ViewHolder viewHolder = null;
			if (CommonUtility.isNull(convertView)) {
				viewHolder = new ViewHolder();
				convertView = inflater.inflate(
						R.layout.item_my_question_xuanshang, null);
				viewHolder.text_content = (TextView) convertView
						.findViewById(R.id.text_content);
				viewHolder.text_cost = (TextView) convertView
						.findViewById(R.id.text_cost);
				viewHolder.text_create_cost_date = (TextView) convertView
						.findViewById(R.id.text_create_cost_date);
				viewHolder.text_content = (TextView) convertView
						.findViewById(R.id.text_content);

				viewHolder.text_cancel_xuanshang = (TextView) convertView
						.findViewById(R.id.text_cancel_xuanshang);
				viewHolder.text_jiedan_time = (TextView) convertView
						.findViewById(R.id.text_jiedan_time);
				viewHolder.text_doctor_name = (TextView) convertView
						.findViewById(R.id.text_doctor_name);
				viewHolder.text_jiedan_status = (TextView) convertView
						.findViewById(R.id.text_jiedan_status);
				viewHolder.text_cancel_xuanshang.setOnClickListener(listener);

				viewHolder.ll_detail = (LinearLayout) convertView
						.findViewById(R.id.ll_detail);
				CommonUtility.setViewHolderTag(convertView, viewHolder);
			} else {
				viewHolder = (ViewHolder) CommonUtility
						.getViewHolderTag(convertView);
			}

			try {
				JSONObject object = (JSONObject) getItem(position);
				JSONObject question = object.getJSONObject("Question");
				convertView.setTag(R.id.tag_obj, object);
				viewHolder.text_cost.setText("￥" + question.getInt("Cost"));
				viewHolder.text_create_cost_date.setText("创建时间："
						+ CommonUtility.formatDate(
								question.getString("Cost_Time"), 0, 16));
				viewHolder.text_content.setText(question.getString("Content"));
				int status = question.getInt("Status");
				if (status == 1) {
					viewHolder.text_jiedan_status.setText("等待接单");
					viewHolder.text_cancel_xuanshang
							.setVisibility(View.VISIBLE);
					viewHolder.text_jiedan_time.setVisibility(View.GONE);
					viewHolder.ll_detail.setVisibility(View.GONE);
					viewHolder.text_cancel_xuanshang.setTag(question);
					viewHolder.text_cancel_xuanshang.setTag(R.id.tag_obj,
							position);
				} else if (status == 2 || status == 3) {
					viewHolder.text_cancel_xuanshang.setVisibility(View.GONE);
					viewHolder.text_jiedan_time.setVisibility(View.VISIBLE);
					viewHolder.text_jiedan_time.setText("接单时间："
							+ CommonUtility.formatDate(
									question.getString("Doctor_Time"), 0, 16));
					String statusText = "已接单";
					if (status == 3) {
						statusText = "已诊断";
					}
					viewHolder.text_jiedan_status.setText(statusText);
					viewHolder.ll_detail.setVisibility(View.VISIBLE);
					StringBuilder sb = new StringBuilder();
					JSONObject jiedan_doctor = object
							.getJSONObject("Doctor_User");
					sb.append(jiedan_doctor.getString("Name"))
							.append("（")
							.append(CommonUtility.convertJSONArray2String(
									jiedan_doctor.getJSONArray("Professional"),
									",")).append(" | ")
							.append(jiedan_doctor.getString("Hospital"))
							.append("）");
					SpannableStringBuilder builder = new SpannableStringBuilder(
							sb);
					// ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
					ForegroundColorSpan blueSpan = new ForegroundColorSpan(
							activity.getResources().getColor(
									R.color.border_blue));
					builder.setSpan(blueSpan, 0, sb.indexOf("（"),
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					viewHolder.text_doctor_name.setText(builder);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		HashMap<String, Object> params;
		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(final View view) {
				final JSONObject question = (JSONObject) view.getTag();
				if (!CommonUtility.isNull(question)) {
					OAlert alert = new OAlert(activity);
					alert.setOK("确认");
					alert.setCancel("取消");
					alert.setTitle("请输入交易密码");
					alert.setContentView(R.layout.view_input_pay_password);
					final EditText edit_pay_password = (EditText) alert
							.findViewById(R.id.edit_pay_password);
					CommonUtility.showKeyboard(edit_pay_password);
					alert.show();
					alert.setListener(new OAlertListener() {

						@Override
						public boolean onOK(OAlert alert) {
							String pay_password = edit_pay_password.getText()
									.toString();
							if (!CommonUtility.isNull(pay_password)) {

								HashMap<String, Object> params = new HashMap<String, Object>();
								params.put("Cost", 0);
								params.put("Is_Cost", 0);
								try {
									params.put("qid", question.getString("Qid"));
								} catch (Exception e) {
									e.printStackTrace();
								}
								params.put(Constant.PARAM_API, "Question.Set");
								params.put(Constant.PARAM_TOKEN,
										GlobalSettings.sToken);
								params.put("PayPwd", OUtil.md5(pay_password));
								RequestTaskIntercept.requestIntercept(activity,
										Constant.URL.REQUEST,
										new RequestHandler(activity,
												new HandlerCallback() {

													@Override
													public void callback(
															Object o) {
														if (!CommonUtility
																.isNull(o)) {
															JSONObject object = (JSONObject) o;
															if (CommonUtility
																	.response200(object)) {
																int position = (Integer) view
																		.getTag(R.id.tag_obj);
																removeIndex(position);
																CommonUtility
																		.toast(activity,
																				"取消成功");
															}
														} else {
															CommonUtility
																	.toast(activity,
																			"取消失败，请稍后再试。");
														}
													}
												}), params);
							} else {
								CommonUtility.toast(activity, "请输入交易密码");
								return true;
							}
							return false;
						}

						@Override
						public boolean onCancel(OAlert alert) {
							return false;
						}
					});
				} else {
					CommonUtility.toast(activity, "操作失败，请稍后再试。");
				}
			}
		};
	}
	
	
/*	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(getContext());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/
}
